var Add_btn = document.querySelector('.bar .addStu');
var cover = document.querySelector(".cover");
var addBox = document.querySelector(".add");
var add_close = document.querySelector(".add .close");
var tbody = document.querySelector('tbody');
var update_btn = document.querySelectorAll(".update");
var add_student = document.querySelector('.add_student');

// 添加学员按钮
var add_btn = document.querySelector('.add .btns input:nth-child(1)');
var add_form = document.querySelector('.add form');
var userName = document.querySelector('.userName input');
var userage = document.querySelector('.userage input');
var userPhone = document.querySelector('.userPhone input');
var userSelary = document.querySelector('.userSelary input');
var userrelSelary = document.querySelector('.userrelSelary input');

var  typeMethods = '';

var stuObj;

// 点击添加学员按钮
Add_btn.addEventListener('click', function () {
  cover.style.display = 'block';
  addBox.style.display = 'block';
  // 用户点击添加学生按钮
  typeMethods = 'Add';
  add_student.innerHTML = '添加学生信息';
  add_btn.value = '添加';

  // 表单信息重置
  add_form.reset();
  // 省市县联动重置数据
  liandong();

});
// 点击关闭学员按钮
add_close.addEventListener('click', function () {
  cover.style.display = 'none';
  addBox.style.display = 'none';
});



// 加载学生信息,默认加载前8条数据
var srartPage = 0;
var pageStep = 5;
var endPage = pageStep;


loadDate();
function loadDate() {
  var stuMsg = localStorage.getItem("studentInfo");
  if (arguments.length == 0) {
    if (stuMsg) {
      stuMsg = JSON.parse(localStorage.getItem("studentInfo")).slice(srartPage, endPage);
    } else {
      stuMsg = [];
    }
  } else {
    stuMsg = arguments[0];
  }
  tbody.innerHTML = '';
  tbody.innerHTML = stuMsg.map(function (item, index) {
    return `<tr> 
                      <td>${index + 1} </td> 
                      <td>${item.stuNum}</td> 
                      <td>${item.stuname}</td> 
                      <td>${item.stuage}</td> 
                      <td>${item.stugender == 1 ? '男' : '女'}</td> 
                      <td>${item.stuZy}</td> 
                      <td>${item.stuGrup}</td> 
                      <td>${item.stuPhone}</td> 
                      <td>${item.stuDreamS}</td> 
                      <td>${item.stuTrueS}</td> 
                      <td>${item.province + item.city + item.county}</td> 
                      <td>
                        <input type="button" value="删除" data-myid=${item.stuNum} class="del">
                        <input type="button" value="编辑" data-myid=${item.stuNum} class="update">
                     </td>
                  </tr>`;
  }).join('');
}




// 数据分页: 每页有8条数据
// 一共有:  20 / 8   如果整除,则就是对应的页码总数,如果没有整除,则页码加1
var pageCount = 0;
var total = document.querySelector('.total');
function loadPage(pages, pagenumber) {

  var stuMsg = localStorage.getItem("studentInfo");
  if (stuMsg) {
    stuMsg = JSON.parse(localStorage.getItem("studentInfo"));
  } else {
    stuMsg = [];
  }

  if (stuMsg.length != 0) {
    pageCount = pages % pagenumber == 0 ? parseInt(pages / pagenumber) : parseInt(pages / pagenumber) + 1;
    total.innerHTML = pageCount;
  }
}
// 动态加载总页数
loadPage(getdatas().length, pageStep);


// 获取本地存储共有多少条数据
function getdatas() {
  var stuMsg = localStorage.getItem("studentInfo");
  if (stuMsg) {
    stuMsg = JSON.parse(localStorage.getItem("studentInfo"));
  } else {
    stuMsg = [];
  }
  return stuMsg;
}


// 添加添加按钮/修改按钮
add_btn.addEventListener('click', function () {
  // 获取性别
  var gender = document.querySelector('.usergender input:checked');
  // 获取专业
  var zhuanye = document.querySelector('.userzhuanye select:nth-child(1)');
  // 获取所在小组
  var xiaozu = document.querySelector('.userzhuanye select:nth-child(2)');
  // 获取省
  var province = document.querySelector('.province').options[document.querySelector('.province').selectedIndex].text;
  // 获取市
  var city = document.querySelector('.city').options[document.querySelector('.city').selectedIndex].text;
  // 获取县
  var county = document.querySelector('.county').options[document.querySelector('.county').selectedIndex].text;
  // 执行添加学生操作
  if(typeMethods == 'Add') {
  
  // 随机产生一个学号
  var rd = 'XH00' + Date.now().toString().substring(5);
  var stu = new Student(rd, userName.value, userage.value, gender.value, zhuanye.value, xiaozu.value, userPhone.value, userSelary.value, userrelSelary.value, province, city, county);

  var stu_ary = getData();

  stu_ary.push(stu);

  // 更新到本地存储中
  localStorage.setItem('studentInfo', JSON.stringify(stu_ary));

 
  }else if(typeMethods == 'update') {
     // 用户点击了编辑按钮,执行编辑操作, 获取当前学生ID
     var up_id;
     var stuMsg = JSON.parse(localStorage.getItem("studentInfo"));
     stuMsg.forEach(function (item, index) {
      if (item.stuNum == stuObj.stuNum) {
        up_id = index;
      }
    });
    //根据当前id获取数组中对应的数据,将数据重新赋值,并保存到本地存储中
    stuMsg[up_id].stuname = userName.value;
    stuMsg[up_id].stuage = userage.value;
    stuMsg[up_id].stugender = gender.value;
    stuMsg[up_id].stuZy = zhuanye.value;
    stuMsg[up_id].stuGrup = xiaozu.value;
    stuMsg[up_id].stuPhone =userPhone.value;
    stuMsg[up_id].stuDreamS = userSelary.value;
    stuMsg[up_id].stuTrueS =userrelSelary.value;
    stuMsg[up_id].province = province;
    stuMsg[up_id].city = city;
    stuMsg[up_id].county = county;

    localStorage.setItem('studentInfo', JSON.stringify(stuMsg));
  }

  loadDate();
  // 加载页码
  loadPage(getdatas().length, pageStep);

  add_close.click();

  add_form.reset();
});

function Student(stuNum, stuname, stuage, stugender, stuZy, stuGrup, stuPhone, stuDreamS, stuTrueS, province, city, county) {
  this.stuNum = stuNum;
  this.stuname = stuname;
  this.stuage = stuage;
  this.stugender = stugender;
  this.stuZy = stuZy;
  this.stuGrup = stuGrup;
  this.stuPhone = stuPhone;
  this.stuDreamS = stuDreamS;
  this.stuTrueS = stuTrueS;
  this.province = province;
  this.city = city;
  this.county = county;
}


function getData() {
  var stuMsg = localStorage.getItem("studentInfo");
  if (stuMsg) {
    stuMsg = JSON.parse(localStorage.getItem("studentInfo"));
  } else {
    stuMsg = [];
  }
  return stuMsg;
}



// 根据学号查询学生信息
var searchStu = document.querySelector('.searchStu');
searchStu.onkeyup = function (e) {

  if (e.key == "Enter") {
    var searchMsg = this.value.trim().toUpperCase();

    var stuData = getData();

    var res = stuData.filter(function (item, index) {
      return item.stuNum == searchMsg;
    });

    if (res.length > 0) {
      loadDate(res);
    }

    this.value = '';
  }
};


// 显示所有学生信息
var showALL = document.querySelector('.showALL');
showALL.onclick = function () {
  loadDate();
};


// 根据学生名字进行模糊查询
var searchName = document.querySelector('.searchName');
searchName.onkeyup = function (e) {
  if (e.key == "Enter") {
    var searchMsg = this.value.trim();

    var stuData = getData();

    var res = stuData.filter(function (item, index) {
      return item.stuname.includes(searchMsg);
    });

    if (res.length > 0) {
      loadDate(res);
    }

    this.value = '';
  }
};



// 省,市,县三级联动
function liandong() {


var s = document.querySelector(".province");
var q = document.querySelector('.city');
var x = document.querySelector('.county');

var sheng = {
  bj: "北京",
  hb: "河北省",
  ln: "辽宁省"
};

var shi = {
  '0': ["昌平区", "海淀区", "大兴区", "朝阳区"],
  '1': ["石家庄", "张家口", "保定", "邯郸", "涿州"],
  '2': ["沈阳", "大连", "鞍山", "本溪"]
};

var qu = {
  '0': [["沙河", "南邵", "宏福苑"], ["中关村", "清华", "北大"], ["黄村", "机场"], ["呼家楼", "三里屯", "劲松"]],
  '1': [["长安区", "桥西区", "新华区", "赵县"], ["张北县", "沽源县", "康保县", "尚义县"], ["涞水", "易县", "定兴"], ["丛台", "肥乡", "永年"], ["松林店镇", "码头镇", "东城坊镇"]],
  '2': [["和平区", "沈河区", "皇姑区", "苏家屯区"], ["甘井子", "沙河口区", "旅顺口区", "金州区", "普兰店区"], ["海城市", "台安县", "铁西"], ["河西区", "河东区", "宫原区", "彩屯区"]]
};



var str = '';
var i = 0;
for (var key in sheng) {
  str += `<option value=${i}>${sheng[key]}</option>`;
  i++;
}
s.innerHTML = '<option>--请选择--</option>' + str;
q.innerHTML = '<option>--请选择--</option>';
x.innerHTML = '<option>--请选择--</option>';
    s.addEventListener('change', function() {
      q.innerHTML = '<option>--请选择--</option>';
      x.innerHTML = '<option>--请选择--</option>';

      var str1 = '';
      shi[this.value].map(function (item, index) {
         str1 += `<option value = ${index}>${item}</option>`;
      });
      q.innerHTML = "<option>--请选择--</option>" + str1; 
    });



   q.addEventListener('change', function(){
    var q1 = '';
    switch (s.value) {
      // 北京
      case "0":
        q1 = qu['0'][this.value].map(function (item, index) {
          return `<option value=${index}>${item}</option>`;
        }).join("");

        break;
  
      // 河北
      case "1":
        q1 = qu['1'][this.value].map(function (item, index) {
          return `<option value=${index}>${item}</option>`;
        }).join("");
        break;
  
      //辽宁
      case "2":
        q1 = qu['2'][this.value].map(function (item, index) {
          return `<option value=${index}>${item}</option>`;
        }).join("");
   
        break;
    }
    x.innerHTML = '<option>--请选择--</option>' + q1;
   });
}
liandong();

// 获取当前页码
var current = document.querySelector('.current');
// 点击下一页
var nextBtn = document.querySelector('.nextBtn');
nextBtn.onclick = function () {
  var p = parseInt(current.innerHTML);
  p++;
  if (p > pageCount) {
    p = pageCount;
    return;
  }
  srartPage += pageStep;
  endPage += pageStep;
  loadDate();
  loadPage(getdatas().length, pageStep);
  current.innerHTML = p;
};


// 点击上一页
var prevBtn = document.querySelector('.prevBtn');
prevBtn.onclick = function () {
  var p = parseInt(current.innerHTML);
  p--;
  if (p == 0) {
    p = 1;
    return;
  }
  srartPage -= pageStep;
  endPage -= pageStep;
  loadDate();
  loadPage(getdatas().length, pageStep);
  current.innerHTML = p;
};


// 修改每页显示数据
var pageSelect = document.querySelector('.pageSelect');
pageSelect.onchange = function () {
  pageStep = parseInt(this.value);
  endPage = pageStep;
  srartPage = 0;
  // 当前页面回到第一页
  current.innerHTML = 1;
  loadPage(getdatas().length, pageStep);
  loadDate();
};


// 点击删除功能
tbody.addEventListener('click', function (e) {
  var del_id;
  if (e.target.className == 'del') {
    // 获取当前数据对应学生编号
    del_id = e.target.dataset.myid;
    var stuMsg = localStorage.getItem("studentInfo");
    if (stuMsg) {
      if (confirm('确定要删除当前数据么')) {
        stuMsg = JSON.parse(localStorage.getItem("studentInfo"));
        // 根据学生编号获取对应的数组id值
        stuMsg.forEach(function (item, index) {
          if (item.stuNum == del_id) {
            del_id = index;
          }
        });
        stuMsg.splice(del_id, 1);
        // 重新将数据跟新回本地存储中
        localStorage.setItem("studentInfo", JSON.stringify(stuMsg));
        // 重新动态加载页码数据
        loadPage(getdatas().length, pageStep);
        // 判断当前页面和总页码的关系
        // 如果当前页码 > 总页面
        var p = parseInt(current.innerHTML);
        if (p > pageCount) {
          srartPage = pageCount * pageStep - pageStep;
          endPage = pageCount * pageStep;
          // 修改当前页码
          current.innerHTML = --p;
        }
        loadDate();
      }

    } else {
      stuMsg = [];
    }
  }
});


// 点击编辑
tbody.addEventListener('click', function (e) {
  if (e.target.className == 'update') {
    // 显示编辑信息窗口
    cover.style.display = 'block';
    addBox.style.display = 'block';

    //当前用户点击了编辑按钮
    typeMethods = 'update';

    add_student.innerHTML = '修改学生信息';

    add_btn.value = '修改';

    liandong();

    // 数据回填
    // 根据当前学生ID获取对应对象信息,将对象信息回填到对应的标签中
    var stuID  = e.target.dataset.myid;
    // 根据当前对象ID获取对应的对象
    var ary = getdatas();
    // 保存对应学生对象信息
    ary.forEach(function(item, index){
          if(item.stuNum == stuID) {
            stuObj = item;
          }
    });
    //数据回填
    userName.value = stuObj.stuname;
    userage.value = stuObj.stuage;
    userPhone.value = stuObj.stuPhone;
    userSelary.value = stuObj.stuDreamS;
    userrelSelary.value = stuObj.stuTrueS;

    // 性别数据回填
    var gender = document.querySelectorAll(`.usergender input`);
    gender.forEach(function(item){
          if(item.value == stuObj.stugender) {
              item.checked = true;
          }
    });
    //获取专业
    var zhuanye = document.querySelector('.userzhuanye select:nth-child(1)');
    zhuanye.value = stuObj.stuZy;

    //获取所在小组
    var xiaozu = document.querySelector('.userzhuanye select:nth-child(2)');
    xiaozu.value = stuObj.stuGrup;


    //籍贯数据回填
    var province = document.querySelector('.province');//.options[document.querySelector('.province').selectedIndex];
    for (let i = 0; i < province.options.length; i++) {
      if (province.options[i].text === stuObj.province) {
        province.selectedIndex = i; // 设置选中项的索引
        break; // 找到后退出循环
      }
    }
    // province.text = stuObj.province;
    //获取市
    var city = document.querySelector('.city').options[document.querySelector('.city').selectedIndex];
    city.text = stuObj.city;

    // 获取县
    var county = document.querySelector('.county').options[document.querySelector('.county').selectedIndex];
    county.text = stuObj.county;
  }
});

